package io.dy.snatch;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

/**
 * @author : dmj
 * @date: 2024/10/11 2:31 下午
 * @description: 模拟抢红包
 */
public class SnatchRedEnvelopThread implements Runnable{

    /**
     * 红包总个数
     */
    private Integer redEnvelopCount;

    /**
     * 红包总金额
     */
    private final BigDecimal totalAmount;

    /**
     * 最小红包金额
     */
    private final BigDecimal minAmount;

    /**
     * 已经被抢红包金额
     */
    private BigDecimal snatchedAmount = BigDecimal.ZERO;


    public SnatchRedEnvelopThread(Integer redEnvelopCount, BigDecimal totalAmount, BigDecimal minAmount) {
        this.redEnvelopCount = redEnvelopCount;
        this.totalAmount = totalAmount;
        this.minAmount = minAmount;
    }

    @Override
    public void run() {
        /**
         * 对红包对象加锁
         */
        synchronized (this){
            //1、判断红包剩余个数 如果剩余个数为0 表示红包被抢完
            if(redEnvelopCount == 0){
                System.err.println(Thread.currentThread().getName() + "手速慢了..... 红包已被抢完！！！！！");
            }else{
                BigDecimal redAmount;
                //2、判断红包个数为1时 用 总金额 - 已经被抢红包金额
                if(redEnvelopCount == 1){
                    redAmount = totalAmount.subtract(snatchedAmount);
                }else{
                    //3、生成总金额范围内的随机数
                    Random random = new Random();
                    redAmount = BigDecimal.valueOf(random.nextDouble()).multiply(totalAmount.subtract(snatchedAmount));

                    //4、判断 如果随机生成的 redAmount 为 0 那么赋值 最小红包金额
                    if(redAmount.compareTo(BigDecimal.ZERO) == 0){
                        redAmount = minAmount;
                    }
                }

                //5、设置红包保留两位小数
                redAmount = redAmount.setScale(2, RoundingMode.HALF_UP);

                //6、设置 已经被抢红包金额
                snatchedAmount = snatchedAmount.add(redAmount);

                //设置红包个数
                redEnvelopCount --;
                System.out.println(Thread.currentThread().getName() + "抢到" + redAmount + "元！！！！");
            }
        }
    }


    public static void main(String[] args) {
        SnatchRedEnvelopThread snatchRedEnvelopThread = new SnatchRedEnvelopThread(5, new BigDecimal("8888.88"), new BigDecimal("0.01"));
        new Thread(snatchRedEnvelopThread, "dy").start();
        new Thread(snatchRedEnvelopThread, "sy").start();
        new Thread(snatchRedEnvelopThread, "dsy").start();
        new Thread(snatchRedEnvelopThread, "zm").start();
        new Thread(snatchRedEnvelopThread, "fd").start();
        new Thread(snatchRedEnvelopThread, "wsy").start();
        new Thread(snatchRedEnvelopThread, "gzl").start();
        new Thread(snatchRedEnvelopThread, "wr").start();
        new Thread(snatchRedEnvelopThread, "zdq").start();
        new Thread(snatchRedEnvelopThread, "csl").start();
    }
}
